package pers.qianyu.month_202011.date_20201116;

import java.util.*;

/**
 * 438. 找到字符串中所有字母异位词
 * https://leetcode-cn.com/problems/find-all-anagrams-in-a-string/
 *
 * @author mizzle rain
 * @date 2020-11-16 13:42
 */
public class FindAnagrams {
    public List<Integer> findAnagrams(String s, String p) {
        ArrayList<Integer> result = new ArrayList<>();
        int left = 0, right = p.length() - 1;
        int[] need = new int[26];
        int[] window = new int[26];
        for (int i = 0; i < p.length(); i++) {
            need[p.charAt(i) - 'a']++;
            if (i < s.length()) {
                window[s.charAt(i) - 'a']++;
            }
        }
        while (right < s.length() - 1) {
            if (isValid(need, window)) {
                result.add(left);
            }
            window[s.charAt(left++) - 'a']--;
            window[s.charAt(++right) - 'a']++;
        }
        if (isValid(need, window)) {
            result.add(left);
        }
        return result;
    }

    private boolean isValid(int[] need, int[] window) {
        for (int i = 0; i < 26; i++) {
            if (need[i] != window[i]) {
                return false;
            }
        }
        return true;
    }

    public static void main(String[] args) {
        String s = "aa";
        String p = "bb";
        List<Integer> result = new FindAnagrams().findAnagrams(s, p);
        System.out.println("result = " + result);
    }
}
